package models;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.Model;
import com.avaje.ebean.SqlUpdate;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import models.utils.Hash;
import play.data.format.Formats;
import play.data.validation.Constraints;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * User entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "user")
public class User extends Model{

    @Id
	public Long userId;

    @Constraints.Required
    @Formats.NonEmpty
	public String userName;

    @Formats.DateTime(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date userCreatetime;

    @Constraints.Required
    @Formats.NonEmpty
	public String userPasswd;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
	public Set<UserPermissionManytomany> userPermissionManytomanies = new HashSet<UserPermissionManytomany>(
			0);

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
    @JsonBackReference
    public Set<Bill> bills = new HashSet<Bill>(0);

    public static Model.Finder<Long, User> find = new Model.Finder<>(User.class);

    public User() {

    }

    public User(String name, String clearPassword) {
        this.userName = name;
        this.changePassword(clearPassword);
    }

    public static User findById(Long id) {
        return find.where().eq("userId", id).findUnique();
    }

    public static List<User> all() {
        return find.all();
    }

    public static User authenticate(Long id, String clearPassword) {

        User user = find.where().eq("id", id).findUnique();
        if (user != null) {
            // get the hash password from the salt + clear password
            if (Hash.checkPassword(clearPassword, user.userPasswd)) {
                return user;
            }
        }
        return null;
    }

    public void changePassword(String clearPassword) {
        this.userPasswd = Hash.createPassword(clearPassword);
        this.save();
    }

}